package practise.leetcode.q8;

public class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        if (str.isEmpty()) {
            return 0;
        }

        boolean isNag = false;
        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (i == 0) {
                if (chars[i] == '-') {
                    isNag = true;
                    continue;
                }
                else if (chars[i] == '+') {
                    continue;
                }
                else if (!isNum(chars[i])) {
                    return 0;
                }
            }

            if (!isNum(chars[i])) {
                break;
            }
            sb.append(chars[i]);
        }

        if (sb.length() == 0) {
            return 0;
        }
        return parseInt(isNag, sb.toString());
    }

    boolean isNum(char c) {
        return c >= '0' && c <= '9';
    }

    int parseInt(boolean isNag, String s) {
        try {
            return isNag ? -1 * Integer.parseInt(s) : Integer.parseInt(s);
        }
        catch (Exception e) {
            return isNag ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
    }
}
